<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8">
        <title>计算属性</title>
        <style type="text/css">
            code { border: 1px solid #d1d1d1; background: #f0f0f0; }
            #root { margin: 15px 0 ; border: 1px solid blue; }
            .item { display: flex ; }
            .item>* { flex-basis: 20%; text-align: center;}
        </style>
    </head>
    <body>

        <h3>计算属性</h3>
        
        <div id="root">
            <input type="text" v-model="familyName" placeholder="姓氏">
            <input type="text" v-model="givenName" placeholder="名字">
            <p> {{ fullName }}</p>
            <hr>
            <div class="list">
                <div class="item" v-for="(item,index) in items" v-bind:key="item.id">
                    <span>{{ index + 1 }}</span>
                    <span>{{ item.name }}</span>
                    <span>{{ item.price }}</span>
                    <span>{{ item.amount }}</span>
                    <span>{{ item.price * item.amount }}</span>
                </div>
                <div class="total">{{ total }}</div>
            </div>
        </div>

        <script src="../scripts/vue@3.2.31.js" type="text/javascript"></script>

        <script type="text/javascript">
            const options = {
                data(){
                    return {
                        familyName: '',
                        givenName: '',
                        items: [
                            { id: 12 , name: '藜蒿炒腊肉' , price: 20 , amount: 1 },
                            { id: 57 , name: '荷包辣椒荷包蛋' , price: 18 , amount: 1 },
                            { id: 19 , name: '大盘鸡' , price: 30 , amount: 1 }
                        ]
                    }
                },
                computed: {
                    fullName(){
                        return this.familyName + this.givenName ;
                    },
                    total(){
                        let reducer = (prev,curr) => prev + curr.price * curr.amount ;
                        let init = 0;
                        let sum = this.items.reduce( reducer , init );
                        return sum ;
                    }
                }
            }
            Vue.createApp(options).mount('#root');
        </script>


    </body>
</html>